<?php
/**
 * 分组
 * @author Administrator
 *
 */

class RoleaService extends Service {

    
    /**
     * @return array 返回用户列表的表头
     */
    public static function indexHeader(){
        $header = array(
            'RoleID' => array('text' => PubFunc::t('分组ID')),
            'RoleName' => array('text' => PubFunc::t('分组名称')),
        	'identity' => array('text' => PubFunc::t('分组身份')),
        	'ViewAllChannel' => array('text' => PubFunc::t('查看全渠道')),
        	'RoleTag' => array('text' => PubFunc::t('运维标志')),
            'Remark' => array('text' => PubFunc::t('备注')),
        	'AddBy' => array('text' => PubFunc::t('创建人')),
        	'AddTime'=> array('text' => PubFunc::t('创建时间')),
        	'EditTime'=> array('text' => PubFunc::t('修改时间')),
            'Action' => array('text' => PubFunc::t('操作'))
        	
        );
        
//         if(!AccAuth::isAdmin()){
//         	unset($header['Action']);
//         }

        return $header;
    }
    
    

    /**
     * 返回列表的信息
     * @return mixed
     */
    public static function indexData($params){
    	$user = AccAuth::me();
    	if(!AccAuth::isAdmin()){
    		$params['AddBy'] = $user['UserID'];
    	}
    	
        $result = array();
        // 查找用户列表
        $modUser = new ModRole();
        $tmp = $modUser->page($params);
        $length = count($tmp['data']);
        $identityList = self::identityList();
        $viewAllChannelList = RoleaService::viewAllChannelList();
        $userList = self::userList();
        foreach($tmp['data'] as $k=>&$v){
        	$type = 1;
        	if($k == 0 && $length == 1){  //当前页只剩下一条数据时，删除之后需显示上一页的数据
        		$type = 2;
        	}
        	$v['AddBy'] = $userList[$v['AddBy']];
        	$v['identity'] = $identityList[$v['identity']];
        	$v['ViewAllChannel'] = $viewAllChannelList[$v['ViewAllChannel']];
        	$v['Action']    = ' <a href="'.PubFunc::buildUrl('/auth/?r=role/edit').'&id='.$v['RoleID'].'&page='.$params['page'].'">编辑</a>';
        	$v['Action']   .= ' <a href="'.PubFunc::buildUrl('/auth/?r=role/grant').'&id='.$v['RoleID'].'" style="color:green;">授权</a>';      	
        	$v['Action']   .= ' <a href="'.PubFunc::buildBackUrl('/auth/?r=role/delete',$type).'&id='.$v['RoleID'].'" style="color:red;" onclick="del()" confirm="是否要删除该分组">删除</a>';
        }
        unset($v);
        return $tmp;
    }

    
    /**
     * 增加一个用户
     * @param $user
     * @return bool|int
     */
    public static function add($role){
        $modRole = new ModRole();

        $addBy   = AccAuth::me('UserID');
        $addTime = date('Y-m-d H:i:s');

        $modRole->RoleName  = $role['RoleName'];
        $modRole->RoleTag  = $role['RoleTag'];
        $modRole->identity  = $role['identity'];
        $modRole->ViewAllChannel = $role['ViewAllChannel'];
        $modRole->Remark    = $role['Remark'];
        $modRole->AddBy     = $addBy;
        $modRole->AddTime   = $addTime;
        $modRole->EditBy     = $addBy;
        $modRole->EditTime   = $addTime;


        if($modRole->save()){
            return $modRole->getDbConnection()->getLastInsertID();
        }else{
            return false;
        }
    }
    
    public static function getById($id){
    	$modRole = new ModRole();
    
    	$role = $modRole->findByPk($id)->attributes;
    
    	if(!empty($role)){
    		return $role;
    	}else{
    		return false;
    	}
    }

    /**
     * 编辑
     * @param $user
     */
    public static function edit($role){  	
        if(PubFunc::checkEmpty($role, array('id'))) return false;

        $modRole = new ModRole();
        
        $editBy   = AccAuth::me('UserID');
        $editTime = date('Y-m-d H:i:s');

        $attr['RoleName']    = $role['RoleName'];
        $attr['Remark']   = $role['Remark'];
        $attr['RoleTag']   = $role['RoleTag'];
        $attr['identity']   = $role['identity'];
        $attr['ViewAllChannel']   = $role['ViewAllChannel'];
        $attr['EditBy']     = $editBy;
        $attr['EditTime']   = $editTime;
        $result = $modRole->updateByPk($role['id'], $attr);
        return $result;
    }

    /**
     * 删除
     * @param unknown $id
     * @return boolean
     */
    public static function delete($id){    	
        try{
            ModRole::model()->deleteAllByAttributes(array('RoleID' => $id));
            ModRoleMenuMap::model()->deleteAllByAttributes(array('RoleID' => $id));
            return true;
        }catch (Exception $e){
            return false;
        }
    }
    
    /**
     * 去重
     * @param number $id  主键id
     * @param unknown $field 检查是否重复的字段名
     * @param unknown $val 检查是否重复的值
     * @return number
     */
    public static function repeat($id = 0, $field, $val){
    	$modRole = new ModRole();
    	$conut = $modRole->repeat($id, $field, $val);
    	return $conut;
    }
    
    public static function grantMenu($role, $add, $delete){
    	if(empty($role)) return false;
    
    	$modMenu = new ModMenu();
    	
    	$menuList = array();
    	foreach($modMenu->select() as $v){
    		$menuList[$v['MenuID']] = $v;
    	}
    	$myMenu = $menuList;
    
    	if(!empty($myMenu)){
    		$menuKey = array_keys($myMenu);
    
    		$add = array_intersect($add, $menuKey);
    		$delete = array_intersect($delete, $menuKey);
    	}
    
    	try{
    		self::beginTransaction();
    		$modRoleMenuMap = new ModRoleMenuMap();
    
    		$modRoleMenuMap->deleteAllByAttributes(array(
    				'RoleID' => $role,
    				'MenuID' => $delete
    		));
    
    		$kv         = array();
    		$addBy      = AccAuth::me('UserID');
    		$addTime    = date('Y-m-d H:i:s');
    		foreach($add as $v){
    			$kv[] = array(
    					'RoleID'    => $role,
    					'MenuID'    => $v,
    					'AddBy'     => $addBy,
    					'AddTime'   => $addTime
    			);
    		}
    
    		$modRoleMenuMap->getDbConnection()->multiInsert($kv, $modRoleMenuMap->getTable(), true);
    
    		self::commit();
    		return true;
    	}catch (Exception $e){
    		self::rollback();
    		return false;
    	}
    }
    
    /**
     * 获取分组列表
     * @param unknown $param
     * is_all为1只能查自己所建的角色，2查到所有
     */
    public static function getRoleList($param,$is_all = 1){
    	$modRole = new ModRole();
    	$user = AccAuth::me();
    	if(!AccAuth::isAdmin() && $is_all == 1){
    		$param['AddBy'] = $user['UserID'];
    	}
    	$data = $modRole->select($param);
    	$roleList = array();
    	foreach ($data as $key=>$val){
    		$roleList[$val['RoleID']] = $val['RoleName'];
    	}
    	return $roleList;
    }
    
    public static function identityList(){
    	$list = array(
    		'1'  =>  '合作商',
    		'2'  =>  '统梦',
    	);
    	return $list;
    }
    
    public static function viewAllChannelList(){
    	$list = array(
    			'1'  =>  '否',
    			'2'  =>  '是',
    	);
    	return $list;
    }

   
} 